package com.fingard.dsp.bank.directbank.abc02;

import com.fingard.FGBiz;
import com.fingard.constant.Format;
import com.fingard.dsp.bank.directConfig.FtpSet;
import com.fingard.io.FileHelper;
import com.fingard.net.FtpPortClient;
import com.fingard.net.FtpReceiver;
import com.fingard.text.StringHelper;
import com.fingard.threading.ThreadPoolUtil;
import com.fingard.util.FtpUtil;
import com.fingard.util.SmbFileUtil;
import com.fingard.util.ZipHelper;

import java.io.*;
import java.util.*;


public class ABC02SyncTask extends ABC02Base {

    private String actNum = "";
    private String dateFrom = "";
    private String dateTo = "";
    private String actCur = "";
    private String receiptSaveToMainDir = "";

    public ABC02SyncTask(String p_actNum, String p_actCur, String p_dateFrom, String p_dateTo) {
        actNum = p_actNum;
        actCur = p_actCur;
        dateFrom = p_dateFrom;
        dateTo = p_dateTo;
    }

    public void download_ftp() {
        ThreadPoolUtil.execute(new Runnable() {
            @Override
            public void run() {
                StringBuilder logSb = new StringBuilder();
                try {
                    setSbLog(logSb);
                    receiptSaveToMainDir = FGBiz.dspCenter.dspSet.receiptMainDir;
                    if (!StringHelper.isNullOrEmpty(receiptSaveToMainDir)) {
                        pushReceiptToATS();
                    } else {
                        WriteBankLogLn("DSPSystem未配置回单文件下载保存主目录");
                    }

                } catch (Exception e) {
                    WriteBankLogLn(e);
                }
            }
        });
    }

    public void pushReceiptToATS() {
        StringBuilder logSb = new StringBuilder();
        String tmpDateFileDir = getTempFileDirectory();
        try {
            //WriteBankLogLn("推送数据到ATS失败");
            setSbLog(logSb);
            Calendar tmpCalendarFrom = Calendar.getInstance();
            tmpCalendarFrom.setTime(Format.Date8Format.parse(dateFrom));

            Calendar tmpCalendarTo = Calendar.getInstance();
            tmpCalendarTo.setTime(Format.Date8Format.parse(dateTo));

            int tmpIntDateFrom = 0;
            int tmpIntDateTo = 0;
            boolean isDown = true;

            String receipt = "";

            //按自然日循环查询
            while (tmpIntDateFrom <= tmpIntDateTo) {
                boolean fileExist = false;
                String recordPath = FGBiz.DSPHOME_Parent + File.separator + "ReceiptRecordData.txt";
                String localSumFilePath = getTempFileDirectory() + File.separator + "SumFile" + File.separator + dateFrom + ".zip";
                StringBuilder json = new StringBuilder();
                if (getBankConfig().getValueAsBool("receiptPushHasTenantId")) {
                    json.append("tenantId=" + FGBiz.dspCenter.dspSet.tenant + "&transType=downloadreceipt&data={\"rows\":[");
                } else {
                    json.append("transType=downloadreceipt&data={\"rows\":[");
                }
                receiptSaveToMainDir = FGBiz.dspCenter.dspSet.receiptMainDir;
                if (fileRead(recordPath, dateFrom)) {
                    WriteBankLogLn(String.format("查询日期：[%s]回单已完成过推送，如需重新推送请删除该日期重新执行", dateFrom));
                    tmpCalendarFrom.add(Calendar.DATE, 1);
                    tmpIntDateFrom = Integer.parseInt(Format.Date8Format.format(tmpCalendarFrom.getTime()));
                    tmpIntDateTo = Integer.parseInt(Format.Date8Format.format(tmpCalendarTo.getTime()));
                    dateFrom = Format.Date8Format.format(tmpCalendarFrom.getTime());
                    fileExist = false;
                    continue;
                }
                List<File> fileList = new ArrayList<File>();
                if (isDown) {
                    FtpSet ftpSet = bankFront.getFtpSet("receipt");
                    File tmpFile = new File(localSumFilePath);
                    if (tmpFile.exists()) {
                        WriteBankLogLn(String.format("针对账号：[%s]，查询日期：[%s]汇总文件已存在无需再次下载", actNum, dateFrom));
                        fileExist = true;
                    }
                    //FTP下载
                    List<String> fileNames = new ArrayList<String>();
                    FtpPortClient ftpPtClient = new FtpPortClient(ftpSet);
                    try {
                        //开启被动传输
                        ftpPtClient.connect();
                        ftpPtClient.list(ftpSet.downDir + "/", ".zip");
                        fileNames = ftpPtClient.arFiles;
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                    if (fileNames != null) {
                        //根据日期匹配要下载的文件
                        for (String f : fileNames) {
                            if (f.contains(dateFrom)) {
                                receipt = receiptSaveToMainDir + File.separator + f.substring(f.lastIndexOf("/") + 1);
                                FtpReceiver tmpReceiver = ftpPtClient.downloadFile(f, receipt);
                                WriteBankLogLn("ftp下载信息：" + tmpReceiver.connMsg);
                                if (tmpReceiver.isCompleted) {
                                    fileExist = true;
                                    WriteBankLogLn(String.format("针对账号：[%s]，查询日期：[%s]下载汇总文件成功", actNum, dateFrom));
                                    WriteBankLogLn("下载的文件名：" + f);
                                } else {
                                    WriteBankLogLn(String.format("针对账号：[%s]，查询日期：[%s]下载汇总文件失败，失败原因：[%s]", actNum, dateFrom, tmpReceiver.connMsg));
                                }
                            }
                        }
                    }
                }
                int tmpFileCount = 0;
                boolean isSaveOnlyFile = false;
                if (fileExist) {
                    WriteBankLogLn("下载到本地的文件名称为：" + receipt);
                    File fileZip = new File(receipt);
                    if (fileZip.exists()) {
                        ZipHelper.unzipFile(fileZip.getPath(), tmpDateFileDir);
                        String dataPath = tmpDateFileDir + File.separator + fileZip.getName().replace(".zip", "");
                        // 再次解压
                        WriteBankLogLn("解压至：" + dataPath);
                        File receiptDir = new File(dataPath);
                        File[] filep = receiptDir.listFiles();
                        for (File receiptFile : filep) {
                            String receip1 = receiptFile.getName();
                            File[] filess = receiptFile.listFiles();
                            if (filess != null) {
                                for (File files : filess) {
                                    String filename = files.getName();
                                    String filenameSpliter[] = filename.split("_");
                                    if (filenameSpliter.length != 8) {
                                        WriteBankLogLn("回单文件:" + filename + "文件名错误");
                                        continue;
                                    }
                                    String receiptUploadShared = this.getBankConfig().getValueAsString("receiptUploadShared");
                                    if (StringHelper.isNullOrEmpty(receiptUploadShared) || "false".equalsIgnoreCase(receiptUploadShared)) {

                                        String tmpByDate = Format.Date8Format.format(new Date());
                                        tmpByDate = tmpByDate.substring(0, 6) + "/" + tmpByDate.substring(6, 8) + "/"
                                                + reqHeader.bankCode + "/" + receip1 + "/";
                                        int result = -1;
                                        String ftpFilePath = "";
                                        String AtsFilePath = "";
                                        if (files.exists()) {
                                            if (!"false".equals(FGBiz.dspCenter.dspSet.receiptShareDir)) {
                                                WriteBankLogLn("正在上传文件至共享目录:" + FGBiz.dspCenter.dspSet.receiptShareDir);
                                                result = SmbFileUtil.smbUploading(files.getPath(), tmpByDate,
                                                        FGBiz.dspCenter.dspSet.receiptShareDir);
                                                AtsFilePath = tmpByDate + filename;//回单文件仓库存储路径
                                            } else {
                                                //ftp服务器
                                                FtpSet ftpSet3 = FGBiz.dspCenter.dspConfig.getReceiptFtpSet("atsReceipt");
                                                WriteBankLogLn("正在上传文件至ftp目录:" + ftpSet3.upDir);
                                                AtsFilePath = tmpByDate + filename;//回单文件仓库存储路径
                                                //上传ftp服务器的地址
                                                ftpFilePath = StringHelper.trimEndFileSp(ftpSet3.upDir) + "/" + AtsFilePath;
                                                WriteBankLogLn("开始将回单" + files.getPath() + "上传至" + ftpFilePath);
                                                //上传至ftp
                                                result = FtpUtil.ftpUploading(ftpSet3, files.getPath(), ftpFilePath);
                                            }
                                        }
                                        String bolend;
                                        if ("D".equals(filenameSpliter[7].substring(0, 1))) {
                                            bolend = "1";
                                        } else {
                                            bolend = "2";
                                        }
                                        if (result == 0 || result == 1) {
                                            //记录上传成功数
                                            tmpFileCount++;
                                            if (result == 0) {
                                                WriteBankLogLn("文件上传成功");
                                            } else {
                                                WriteBankLogLn("文件已存在共享目录无需重复上传");
                                            }
                                            json.append("{");
                                            json.append("\"actNum\":\"" + filenameSpliter[2] + "\",");
                                            json.append("\"actCur\":\"" + "1" + "\",");
                                            json.append("\"receiptCode\":\"" + filenameSpliter[6].substring(0, 20) + "\",");//回单编号
                                            json.append("\"receiptType\":\"" + "" + "\",");//回单类型  1：存款回单；2：取款回单；3：转账回单；4：缴税回单；5：收费回单；6定期回单；7：活期回单
                                            json.append("\"receiptState\":\"" + "" + "\",");//回单状态 1：正常；2：冲正；3：被冲正；4：当日冲正
                                            json.append("\"oppActName\":\"" + "" + "\",");
                                            json.append("\"oppActNum\":\"" + filenameSpliter[4] + "\",");
                                            json.append("\"amount\":\"" + filenameSpliter[5] + "\",");
                                            json.append("\"moneyway\":\"" + bolend + "\",");
                                            json.append("\"tranSeqNo\":\"" + filenameSpliter[3] + "\",");
                                            json.append("\"tranCode\":\"" + "" + "\",");//交易码?
                                            json.append("\"tranDate\":\"" + Format.Date10Format.format(Format.Date8Format.parse(filenameSpliter[1])) + "\",");
                                            json.append("\"filePath\":\"" + AtsFilePath + "\",");//回单文件仓库存储路径
                                            json.append("\"fileType\":\"1\"");
                                            json.append("},");
                                        } else {
                                            WriteBankLogLn("上传文件至共享目录失败，请检查共享目录配置是否正确");
                                            continue;
                                        }
                                    } else {
                                        //保险


                                    }
                                }
                            }
                            //回单循环
                        }
                    }

                    if (tmpFileCount > 0) {
                        json.deleteCharAt(json.length() - 1);
                        json.append("]}");
                        WriteBankLogLn("推送数据到ATS的数据为：" + json.toString());
                        String[] data = sendToATS(json.toString());
                        if (data[0].length() == 0 && data[1].equals("ok")) {
                            WriteBankLogLn("推送数据到ATS成功,请查看数据");
                        } else {
                            WriteBankLogLn("推送数据到ATS失败");
                        }
                    } else {
                        WriteBankLogLn("成功保存文件条数为0，不需要推送数据到ATS");
                    }
                }


                StringBuilder datelog = new StringBuilder();
                datelog.append(dateFrom);
                datelog.append("|");
                writeFile(recordPath, datelog.toString());
                tmpCalendarFrom.add(Calendar.DATE, 1);
                tmpIntDateFrom = Integer.parseInt(Format.Date8Format.format(tmpCalendarFrom.getTime()));
                tmpIntDateTo = Integer.parseInt(Format.Date8Format.format(tmpCalendarTo.getTime()));
                dateFrom = Format.Date8Format.format(tmpCalendarFrom.getTime());
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                String tmpDateDir = Format.DateForLogFormat.format(new Date()).replace("-", File.separator);
                String tmpSubFileName = FGBiz.dspCenter.bankLogsFirstDir + File.separator + tmpDateDir + File.separator + "ABC02" + File.separator + "SyncTask-downloadReceipt" + "_" + actNum + "_" + Format.DateTime17Format.format(new Date()) + "_" + UUID.randomUUID() + ".txt";
                String tmpLogFile = FGBiz.dspCenter.bankLogsDirPath + File.separator + tmpSubFileName;
                FileHelper.writeFile(tmpLogFile, logSb);
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }

    public static boolean fileRead(String filePath, String chars) throws Exception {
        File file = new File(filePath);
        BufferedReader bReader = null;
        FileReader reader = null;
        try {
            if (file.exists()) {
                reader = new FileReader(file);
                bReader = new BufferedReader(reader);
                StringBuilder sb = new StringBuilder();
                String s = "";
                while ((s = bReader.readLine()) != null) {
                    sb.append(s);
                }
                bReader.close();
                String str = sb.toString();
                return str.contains(chars);
            }
        } catch (Exception e) {
            System.out.println(e.getMessage());
        } finally {
            try {
                if (bReader != null) {
                    bReader.close();
                }
                if (reader != null) {
                    reader.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return false;
    }


    /**
     * 将字符串追加到文件已有内容后面
     *
     * @param fileFullPath 文件完整地址：D:/test.txt
     * @param content      需要写入的
     */
    public static void writeFile(String fileFullPath, String content) {
        FileOutputStream fos = null;
        try {
            File tmpFile = new File(fileFullPath);
            File parentDir = new File(tmpFile.getParent());
            if (!parentDir.exists()) {
                parentDir.mkdirs();
            }
            if (!tmpFile.exists()) {
                tmpFile.createNewFile();
            }
            //true不覆盖已有内容
            fos = new FileOutputStream(fileFullPath, true);
            //写入
            fos.write(content.getBytes());
            // 写入一个换行
            fos.write("\r\n".getBytes());
            fos.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (fos != null) {
                    fos.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }


    static boolean delFile(File file) {
        if (!file.exists()) {
            return false;
        }

        if (file.isDirectory()) {
            File[] files = file.listFiles();
            for (File f : files) {
                delFile(f);
            }
        }
        return file.delete();
    }

}
